package com.gec.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gec.model.dto.SysLoginLogDto;
import com.gec.model.system.SysLoginLog;
import com.gec.model.vo.LastMonthLoginLogVo;
import com.gec.model.vo.PageVo;
import com.gec.model.vo.SysLoginLogQueryVo;
import com.gec.system.mapper.SysLoginLogMapper;
import com.gec.system.service.SysLoginLogService;
import com.gec.system.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统访问记录 服务实现类
 * </p>
 *
 * @author llt
 * @since 2023-04-20
 */
@Service
@Transactional
public class SysLoginLogServiceImpl extends ServiceImpl<SysLoginLogMapper, SysLoginLog> implements SysLoginLogService {


    @Autowired
    private SysLoginLogMapper sysLoginLogMapper;
    @Override
    public Result getLoginLogPage(Integer pageNum, Integer pageSize, SysLoginLogDto sysLoginLogDto) {
        //条件查询登录日志(动态 SQL)
        LambdaQueryWrapper<SysLoginLog> queryWrapper = new LambdaQueryWrapper<>();
        //模糊匹配用户名
        queryWrapper.like(StringUtils.hasText(sysLoginLogDto.getUsername()),
                SysLoginLog::getUsername, sysLoginLogDto.getUsername());
        //匹配访问时间
        queryWrapper
                .gt(!StringUtils.isEmpty(sysLoginLogDto.getCreateTimeBegin()),
                        SysLoginLog::getCreateTime, sysLoginLogDto.getCreateTimeBegin())
                .lt(!StringUtils.isEmpty(sysLoginLogDto.getCreateTimeEnd()),
                        SysLoginLog::getCreateTime, sysLoginLogDto.getCreateTimeEnd());
        //时间排序
        queryWrapper.orderByDesc(SysLoginLog::getCreateTime);
        //分页查询
        Page<SysLoginLog> loginLogPage = new Page<>(pageNum, pageSize);
        page(loginLogPage, queryWrapper);
        //封装 vo
        PageVo pageVo = new PageVo(loginLogPage.getRecords(), loginLogPage.getTotal());
        return Result.ok(pageVo);
    }

    @Override
    public void recordLoginLog(String username, String ipaddr, Integer status, String msg) {
        //插入登录日志数据
        SysLoginLog sysLoginLog = new SysLoginLog();
        sysLoginLog.setUsername(username);
        sysLoginLog.setIpaddr(ipaddr);
        sysLoginLog.setStatus(status);
        sysLoginLog.setMsg(msg);

        save(sysLoginLog);
    }

    @Override
    public Result getLastMonthLoginLog() {
        //最近一个月时间登录统计
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        //过去一月
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
//        String mon = format.format(m);
//        System.out.println("过去一个月："+mon);

        //查询数据库
        LambdaQueryWrapper<SysLoginLog> queryWrapper = new LambdaQueryWrapper<>();
        //查询最近一个月记录
        queryWrapper.gt(SysLoginLog::getCreateTime, m);
        queryWrapper.orderByAsc(SysLoginLog::getCreateTime);
        List<SysLoginLog> lastMonthLoginLogs = list(queryWrapper);

        //整理数据,只返回日期时间以及统计数量
        SimpleDateFormat formatDay = new SimpleDateFormat("MM-dd");
        List<String> dayList = lastMonthLoginLogs.stream()
                .map(log -> formatDay.format(log.getCreateTime()))
                .collect(Collectors.toList());
        //对日期分组统计
        Map<String, List<String>> map = dayList.stream()
                .collect(Collectors.groupingBy(day -> day));
        //封装到 list里
        List<LastMonthLoginLogVo> list = new ArrayList<>();
        for (String day : map.keySet()) {
            List<String> countList = map.get(day);
            LastMonthLoginLogVo loginLogVo =
                    new LastMonthLoginLogVo(day, countList.size());
            list.add(loginLogVo);
        }
        //排序
        list = list.stream()
                .sorted(Comparator.comparing(LastMonthLoginLogVo::getDay))
                .collect(Collectors.toList());

        return Result.ok(list);
    }

    @Override
    public IPage<SysLoginLog> selectPage(long page, long limit, SysLoginLogQueryVo sysLoginLogQueryVo) {
        //创建page对象
        Page<SysLoginLog> pageParam = new Page(page,limit);
        //获取条件值
        String username = sysLoginLogQueryVo.getUsername();
        String createTimeBegin = sysLoginLogQueryVo.getCreateTimeBegin();
        String createTimeEnd = sysLoginLogQueryVo.getCreateTimeEnd();
        //封装条件
        QueryWrapper<SysLoginLog> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(username)) {
            wrapper.like("username",username);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.le("create_time",createTimeEnd);
        }
        //调用mapper方法
        IPage<SysLoginLog> pageModel = sysLoginLogMapper.selectPage(pageParam, wrapper);
        return pageModel;
    }
}
